<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="js/vue.js"></script>
  <style>
    .main {
      width: 125px;
      margin: 0 auto;
    }
    button{
      display: block;
      width: 100%;
      color: #fff;
      background-color: #39f;
      border: 0;
      padding: 6px;
      text-align: center;
      font-size: 12px;
      border-radius: 4px;
      cursor: pointer;
      outline: none;
      position: relative;
    }
    button:active{
      top:1px;
      left: 1px;
    }
    .dropdown{
      width: 100%;
      height: 150px;
      margin: 5px 0;
      font-size: 12px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 1px 6px rgba(0,0,0,0.2);
    }
    .dropdown p{
      padding: 6px;
    }
  </style>
</head>
<body>
  <div id="app" v-cloak>
    <div class="main"  v-clickoutside="handleClose">
      <button @click="show = !show">点击显示下拉菜单</button>
      <div class="dropdown" v-show="show">
        <p>我是下拉菜单里面的内容</p>
      </div>
    </div>
  </div>
  <script>
    //自定义指令
    Vue.directive('clickoutside', {
      //bind: 只调用一次, 指令第一次绑定到元素时调用,用这个钩子函数可以定义在绑定时执行一次的初始化动作
      bind:function(el, binding, vnode) {
        console.log(el, binding, vnode)
        function documentHandle(e) {
          console.log(e);
          if(el.contains(e.target)){
            return false;
          }
          if(binding.expression) {
            binding.value(e);
          }
        }
        el.__vueClickOutSide__ = documentHandle;
        document.addEventListener('click', documentHandle)
      },
      unbind:function(el, binding) {
        document.removeEventListener('click', el.__vueClickOutSide__);
        delete el.__vueClickOutSide__;
      }
    })
    var app = new Vue({
      el: '#app',
      data: {
        show: false
      },
      methods: {
        handleClose() {
          this.show = false;
        }
      }
    })
  </script>
</body>
</html>